package com.fable.web.controller.user;

import com.alibaba.fastjson.JSON;
import com.fable.biz.operate.AdminRoleService;
import com.fable.biz.operate.CreateAdminRoleModel;
import com.fable.common.config.RequireLogin;
import com.fable.common.constant.FableConstant;
import com.fable.common.utils.JsonResult;
import com.fable.dal.model.AdminRoleDO;
import com.fable.dal.model.AdminRoleQuery;
import com.fable.dal.model.AdminUserDO;
import com.fable.web.controller.base.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by weishuai on 18/7/21.
 */
@Controller
@RequireLogin
@RequestMapping("/user")
public class AdminRoleController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    AdminRoleService adminRoleService;


    @RequestMapping("/adminRoleList.htm")
    public String list( ModelMap model) {
        AdminRoleQuery roleQuery=new AdminRoleQuery();
        roleQuery.createCriteria().andStatusGreaterThanOrEqualTo(0);
        roleQuery.setOrderByClause(" id desc");
        List<AdminRoleDO> list= adminRoleService.selectByQuery(roleQuery);
        model.put("list", list);
        return "user/adminRoleList";
    }

    @RequestMapping("/adminRoleAdd.htm")
    public String add(HttpServletRequest request, ModelMap model,Integer id) {
        //id不为空则说明是点击修改过来的
        if(id!=null){
            AdminRoleDO adminRoleDO= adminRoleService.selectByPrimaryKey(id);
            model.put("result",adminRoleDO);
        }
        return "user/adminRoleAdd";
    }

    @RequestMapping("/delAdminRole.json")
    @ResponseBody
    public JsonResult delete(HttpServletRequest request, Integer id) {
        JsonResult result = new JsonResult();
//        AdminUserDO adminDO = (AdminUserDO) request.getSession().getAttribute(FableConstant.USER_SESSION_KEY);
//        if (adminDO == null) {
//            result.setErrMsg("请重新登录!");
//            return result;
//        }
        if (id != null) {
            AdminRoleDO adminRoleDO = adminRoleService.selectByPrimaryKey(id);
            if (adminRoleDO == null) {
                result.setErrMsg("对象不存在!");
                return result;
            } else {
                adminRoleDO.setStatus(-1);
                adminRoleService.update(adminRoleDO);
            }
        }
        return result;
    }

    @RequestMapping("/saveAdminRole.json")
    @ResponseBody
    public JsonResult saveAdminRole(HttpServletRequest request, @ModelAttribute CreateAdminRoleModel createAdminRoleModel) {
        JsonResult jsonResult = new JsonResult();
//        AdminUserDO adminDO = (AdminUserDO) request.getSession().getAttribute(FableConstant.USER_SESSION_KEY);
//        if (adminDO == null) {
//            jsonResult.setCustomErrCode("-1", "未登录");
//            return jsonResult;
//        }
        try {
            if (checkExist(createAdminRoleModel)) {
                jsonResult.setErrMsg("已存在角色!");
                return jsonResult;
            }
            if (createAdminRoleModel.getId() != null) {
                AdminRoleDO adminRoleDO = adminRoleService.selectByPrimaryKey(createAdminRoleModel.getId());
                if(adminRoleDO==null){
                    logger.error("非法操作,param:{}", JSON.toJSONString(createAdminRoleModel));
                    jsonResult.setErrMsg("非法操作!");
                    return jsonResult;
                }

                BeanUtils.copyProperties(createAdminRoleModel, adminRoleDO);
                adminRoleService.update(adminRoleDO);
            }else{
                AdminRoleDO adminRoleDO=new AdminRoleDO();
                BeanUtils.copyProperties(createAdminRoleModel, adminRoleDO);
                adminRoleService.add(adminRoleDO);
            }
        } catch (Exception e) {
            logger.error("保存角色异常,param:{}", JSON.toJSONString(createAdminRoleModel), e);
            jsonResult.setErrMsg("保存异常请联系管理员!");
            return jsonResult;
        }
        return jsonResult;
    }

    private boolean checkExist(@ModelAttribute CreateAdminRoleModel createAdminRoleModel) {
        AdminRoleQuery query=new AdminRoleQuery();
        query.createCriteria().andStatusGreaterThanOrEqualTo(0).andNameEqualTo(createAdminRoleModel.getName());
        List<AdminRoleDO> list=adminRoleService.selectByQuery(query)  ;
        if(!CollectionUtils.isEmpty(list)){
            logger.warn("已存在角色,param:{}", JSON.toJSONString(createAdminRoleModel));
            return true;
        }
        return false;
    }
}
